<template>
  <view class="search-container">
    <navBar v-if="isShowCustomNavBar" :navbarData="navbarData"></navBar>
    <tabBar :nowPages="nowPages"></tabBar>
    <!-- <movable-area style="width:100vw;" :style="{ height: whMovablearea }">
      <movable-view style="z-index:1000;" :x="x" :y="y" friction="10" inertia="false" direction="all" :animation="moveAnimation"><onlineService></onlineService></movable-view> -->
    <onlineService></onlineService>
    <!-- 搜索商品 -->
    <view class="container" :class="isIpx ? 'fix-iphonex-container' : ''">
      <view class="top_search">
        <view class="search_read_only">
          <navigator class="search_content" open-type="switchTab" url="/pages/category/category" hover-class="none">
            <block v-if="brandType == 2">
              <image class="search-small-icon" src="https://100000057-1252208446.cos.ap-shanghai.myqcloud.com/images/miniprogram/iocn_search.png" mode="widthFix"></image>
            </block>
            <block v-else><i class="iconfont icon-fangdajing"></i></block>
            <input placeholder-class="phcolor" class="search_input" placeholder-style="color:#ccc;" placeholder="搜索商品" />
          </navigator>
        </view>
      </view>
      <!-- 分类 -->
      <view class="classify" :style="{ height: windowHeight + 'px' }">
        <!-- 一级分类列表 -->
        <scroll-view class="classify_catetory" scroll-y scroll-with-animation="true" :style="{ height: windowHeight + 'px' }">
          <view class="name" v-for="(item, index) in rootcateList" :key="index">
            <view
              :class="activeIndex == index ? 'active' : ''"
              :data-index="index"
              :data-navId="item.navId"
              :data-navType="item.navType"
              :data-urlPath="item.urlPath"
              :data-foreignId="item.foreignId"
              :data-navName="item.navName"
              :data-hasChild="item.parameters.hasChild"
              :data-hideSort="item.parameters.hideSort"
              :data-showFilter="item.parameters.showFilter"
              :data-isSpecial="item.parameters.isSpecial"
              :style="item.parameters.categoryColor"
              @click="changeCate"
              v-if="item.visible"
            >
              {{ item.navName }}
            </view>
          </view>
        </scroll-view>
        <!-- 二级分类列表 -->
        <scroll-view class="classify_detail" scroll-y scroll-with-animation="true" :style="{ height: windowHeight + 'px' }">
          <view class="children" v-if="childcateList">
            <view class="children_item" v-for="(secondItem, index) in childcateList" :key="index" @click="jumpPage" hover-class="none">
              <view :class="secondItem.select ? 'children-space' : ''">
                <block v-if="secondItem.visible">
                  <image class="child_image" :src="secondItem.imageUrl"></image>

                  <view
                    :data-navType="secondItem.navType"
                    :data-urlPath="secondItem.urlPath"
                    :data-foreignId="secondItem.foreignId"
                    :data-navName="secondItem.navName"
                    :data-notShowChildren="secondItem.parameters.notShowChildren"
                    :data-hideSort="secondItem.parameters.hideSort"
                    :data-showFilter="secondItem.parameters.showFilter"
                    :data-isSpecial="secondItem.parameters.isSpecial"
                    :data-navId="secondItem.navId"
                    :style="secondItem.parameters.categoryColor"
                    :class="filterChecked.filterChecked(secondItem.navName, '折扣') ? 'sale' : 'child_name'"
                  >
                    {{ secondItem.navName }}
                    <block v-if="secondItem.parameters.navTag && !!filterChecked.filterNavTag(secondItem.parameters.navTagStartTime, secondItem.parameters.navTagEndTime)">
                      <span
                        style="vertical-align:4px; padding-left: 10rpx;"
                        :style="{ color: secondItem.parameters.navTagColor, 'font-size': secondItem.parameters.navTagFontSize }"
                      >
                        {{ secondItem.parameters.navTag }}
                      </span>
                    </block>
                  </view>
                </block>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <!-- </movable-area> -->
  </view>
</template>

<script module="filterChecked" lang="wxs" src="@/utils/filter.wxs"></script>
<script>
import api from '@/api/api';
import NavBar from '@/components/common/navbar';
import TabBar from '@/components/common/tabbar';
import onlineService from '@/components/common/onlineService';
import { SYSTEM_INFO, SEL_CLASS_CODE, SEL_ACTIVE_CODE, MERCHANT_INFO, CUSTOMER_INFO, CART_KEY, LOWER_WX_VERSION } from '@/utils/constant';
import tip from '@/utils/tip';

export default {
  config: {
    navigationBarTitleText: '分类',
    navigationStyle: 'custom'
  },
  components: {
    navBar: NavBar,
    onlineService: onlineService,
    tabBar: TabBar
  },

  data() {
    return {
      isSale: true,
      isClassify: true,
      isIpx: false,
      isShowCustomNavBar: true,
      nowPages: '',
      scrollTop: 100,
      windowHeight: 0,
      // 默认选中id
      activeIndex: -1,
      activeCode: 0,
      list: {},
      //一级分类数据
      rootcateList: {},
      //二级三级分类数据
      childcateList: {},
      // 传到NavBar 的数据
      navbarData: {
        showCapsule: 1 //是否显示左上角图标   1表示显示    0表示不显示
        // title: '分类',//导航栏 中间的标题
      },
      // 品牌信息 0：三仟院  1：ICH  2:PB
      brandType: getApp().globalData.brandType
    };
  },
  onLoad() {
    let that = this;
    let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
    that.getCurrentMerchantInfo();
    let systemInfo = uni.getStorageSync(SYSTEM_INFO);
    if (Number(systemInfo.SDKVersion) < Number(LOWER_WX_VERSION)) {
      this.isShowCustomNavBar = false;
    }
    this.windowHeight = systemInfo.windowHeight;
    this.isIpx = getApp().globalData.isIpx;
    let pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    this.nowPages = currPage.route;
  },
  onShow(){
   getApp().cl_tracker.track('mini_program_view', {
         path:  this.nowPages,
         pageName: '分类',
       })
  },
  methods: {
    // 重新获取商户信息
    getCurrentMerchantInfo: async function() {
      let that = this;
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
      let merchantId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantId || '';
      let storeId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId || '';
      if (merchantInfo) {
        this.getRootCateTopLevel(merchantInfo.cloudMerchantStoreId);
      } else {
        // 获取商户信息
        const accountInfo = uni.getAccountInfoSync(); // 小程序appId
        let merchantInfo = await api.merchantInfo(accountInfo.miniProgram.appId);
        if (merchantInfo.code === 200) {
          this.getRootCateTopLevel(merchantInfo.data.cloudMerchantStoreId);
          // 存储商户信息
          uni.setStorageSync(MERCHANT_INFO, merchantInfo.data);
        }
      }
    },

    changeCate(e) {
      let navtype = e.target.dataset.navtype, // 导航类型
        urlPath = e.target.dataset.urlpath, // 分类跳转页面
        classId = e.target.dataset.foreignid, // 分类id
        className = e.target.dataset.navname, //分类名称
        hasChild = e.target.dataset.haschild || 1, // 是否显示子分类  1显示     0不显示
        isSort = e.target.dataset.hidesort, // 是否显示排序    0显示     1不显示
        isFilter = e.target.dataset.showfilter, // 是否显示筛选    0不显示   1显示
        isAppend = e.target.dataset.isspecial, // 是否显示悬浮图  0不显示   1显示
        navId = e.target.dataset.navid; // 导航id    用于调导航（二级分类）接口的参数
      if (hasChild == 0) {
        if (navtype == 'link') {
          uni.navigateTo({
            url: '/pages/cms/page?identifier=' + urlPath + '&preview=false'
          });
        } else {
          // uni.switchTab({
          uni.relaunch({
            url:
              '/pages/category/category?cateCode=' +
              classId +
              '&title=' +
              className +
              '&hasChild=' +
              hasChild +
              '&isSort=' +
              isSort +
              '&isFilter=' +
              isFilter +
              '&isAppend=' +
              isAppend +
              '&navId=' +
              navId
          });
        }
      } else if (hasChild == 1) {
        if (navtype == 'link') {
          uni.navigateTo({
            url: '/pages/cms/page?identifier=' + urlPath + '&preview=false'
          });
        } else {
          this.getChildCate(navId);
        }
      }
      //设置一级分类的选中状态
      this.activeIndex = e.currentTarget.dataset.index;
      uni.setStorageSync(SEL_CLASS_CODE, navId);
      uni.setStorageSync(SEL_ACTIVE_CODE, this.activeIndex);
    },

    jumpPage(e) {
      let that = this;
      let navtype = e.target.dataset.navtype, // 导航类型
        urlPath = e.target.dataset.urlpath, // 分类跳转页面
        classId = e.target.dataset.foreignid, // 分类id
        className = e.target.dataset.navname, //分类名称
        showChild = e.target.dataset.notshowchildren, // 是否显示子分类  0显示     1不显示
        isSort = e.target.dataset.hidesort, // 是否显示排序    0显示     1不显示
        isFilter = e.target.dataset.showfilter, // 是否显示筛选    0不显示   1显示
        isAppend = e.target.dataset.isspecial, // 是否显示悬浮图  0不显示   1显示
        navId = e.target.dataset.navid; // 导航id    用于调导航（三级分类）接口的参数
      if (navtype == 'category') {
        uni.vibrateShort({
          complete(res) {
            uni.navigateTo({
              url:
                '/pages/item/search?cateCode=' +
                classId +
                '&title=' +
                className +
                '&showChild=' +
                showChild +
                '&isSort=' +
                isSort +
                '&isFilter=' +
                isFilter +
                '&isAppend=' +
                isAppend +
                '&navId=' +
                navId
            });
          }
        });
      } else if (navtype == 'link') {
        uni.navigateTo({
          url: '/pages/cms/page?identifier=' + urlPath
        });
      } else {
        return;
      }
    },

    // 获取一级分类
    getRootCateTopLevel: async function(storeId) {
      let that = this;
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
      const json = await api.merchantNavigation({
        query: {
          parent_nav_id: 0,
          store_id: storeId
        }
      });
      if (json.code === 1000) {
        // 一级列表
        this.rootcateList = json.data.content;
        if (this.rootcateList.length > 0) {
          let rootcategory = [];
          let showRootCategoryIndex = -1;
          let showRootCategoryCode = -1;
          /*获取二级分类数据*/
          let selCode = uni.getStorageSync(SEL_CLASS_CODE);
          let firstCategory = [];
          for (var i = 0; i < this.rootcateList.length; i++) {
            firstCategory.push(this.rootcateList[i].navId);
            if (this.rootcateList[i]['parameters']) {
              this.rootcateList[i].parameters = JSON.parse(this.rootcateList[i]['parameters']);
            }
            if (showRootCategoryIndex == -1 && this.rootcateList[i].visible == 1) {
              showRootCategoryIndex = i;
              showRootCategoryCode = this.rootcateList[i].navId;
            }
          }
          if (showRootCategoryIndex != -1 && showRootCategoryCode != -1) {
            selCode = parseInt(showRootCategoryCode);
            this.activeIndex = showRootCategoryIndex;
            uni.setStorageSync(SEL_CLASS_CODE, showRootCategoryCode);
            uni.setStorageSync(SEL_ACTIVE_CODE, showRootCategoryIndex);
          }
          if (selCode.length != 0 && firstCategory.indexOf(selCode) != -1) {
            this.activeCode = selCode;
            this.activeIndex = uni.getStorageSync(SEL_ACTIVE_CODE);
            this.getChildCate(this.activeCode);
          } else {
            this.activeIndex = -1;
            this.childcateList = [];
          }
        }
      } else {
        // tip.plainText(json.msg);
      }
    },

    /*
     *    获取二级分类
     * */

    getChildCate: async function(rootCateCode) {
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
      const json = await api.merchantNavigation({
        query: {
          parent_nav_id: rootCateCode,
          store_id: merchantInfo.cloudMerchantStoreId
        }
      });
      if (json.code === 1000) {
        // 二三级分类列表
        let category = json.data.content;
        let subNavigation = [];
        //解析每个数组下面的items.parameters属性
        for (let i = 0; i < category.length; i++) {
          // 解析字符串为数组
          if (category[i]['parameters']) {
            category[i].parameters = JSON.parse(category[i]['parameters']);
          }
          if (category[i].parameters['categoryGroup'] !== null && category[i].parameters['categoryGroup'] > 0) {
            subNavigation.push(category[i]);
          } else {
            category[i].parameters['categoryGroup'] = -1;
            subNavigation.push(category[i]);
          }
        }
        subNavigation.sort(function(a, b) {
          return a.parameters.categoryGroup - b.parameters.categoryGroup;
        });
        for (let j = 0; j < subNavigation.length - 1; j++) {
          if (subNavigation[j].parameters['categoryGroup'] != subNavigation[j + 1].parameters['categoryGroup']) {
            subNavigation[j].select = true;
          }
        }
        this.childcateList = subNavigation;
      } else {
        // tip.plainText(json.msg);
      }
    },

    onShareAppMessage: function(res) {
      if (res.from === 'button') {
      } else {
        this.$EFSTracking.trackingAction('SHARE_CARD', res.from, {});
      }
	  let shareTitle = uni.getStorageSync('storeName') || 'THE MACALLAN EBOUTIQUE麦卡伦'
	  let path = '/pages/item/category'
	  let shareImg = ''
    this.$commonSensors.sensorsPageShare()
		this.$sr.setContext({ share_title: shareTitle || 'THE MACALLAN EBOUTIQUE麦卡伦' });
	  return this.$commonFunction.commonShare(res, shareTitle, path, shareImg);
    },

    // onShareTimeline() {
    //   return {
    //     title: uni.getStorageSync('storeName') || '小程序店铺',
    //     query: ''
    //   };
    // }
  }
};
</script>
<style lang="less" scoped>
.container {
  margin-bottom: 110rpx;
}

.fix-iphonex-container {
  margin-bottom: 150rpx;
}

.search_read_only .search_content {
  width: 100%;
}

.active {
  color: #333;
}

.classify {
  display: flex;
  position: relative;
  overflow: hidden;

  .classify_catetory {
    width: 200rpx;
    position: relative;
    z-index: 1;

    .name {
      color: #999;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;

      view {
        color: #999;
        line-height: 2.5;
      }

      .active {
        background: #fff;
        color: #444;
      }
    }
  }

  .classify_detail {
    position: relative;
    z-index: 1;
    background: #fff;

    .title {
      font-size: 30rpx;
      color: #333;
      margin-left: 25rpx;
    }

    .children {
      display: flex;
      flex-wrap: wrap;
      padding-bottom: 68rpx;
    }

    .child_image {
      width: 60px;
      height: 60px;
    }

    .child_name {
      color: #444;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 170rpx;
    }

    .children_item {
      height: 200rpx;
      width: 32%;
      text-align: center;
    }

    .children-space {
      padding-bottom: 68rpx;
    }
  }
}

.classify {
  background-color: #fff;
  padding: 36rpx 32rpx 0;
}

.classify .classify_catetory {
  width: 41.5%;
  height: auto;
}

.classify .classify_catetory .active {
  border-left: 0;
}

.classify .classify_detail .children_item {
  height: auto;
  width: 100%;
  text-align: left;
}

.classify .classify_detail .children_item.sale {
  color: #ff571a;
}

.classify .classify_detail .children_item .child_image {
  display: none;
}

.classify .classify_detail .child_name {
  width: 100%;
  padding: 0;
  line-height: 2.5;
  font-size: 26rpx;
}

.classify .classify_detail {
  width: 58%;
}

.search_input {
  margin-left: 10rpx;
  padding: 4px 11px 4px 0;
}

.search_read_only .search_content {
  border-radius: 0;
  padding: 0 0 5px;
  background: none;
  border-bottom: 1px solid #e7e7e7;
}

.search_read_only {
  padding: 0 24rpx;
  width: auto;
}

.icon-fangdajing {
  font-size: 36rpx;
  margin-top: -1px;
}

.phcolor {
  color: #ccc;
}

.classify .classify_detail .sale {
  color: #ff571a;
  padding: 0;
  line-height: 2.5;
}

.classify .classify_detail .child_name.sale {
  color: #ff571a;
  line-height: 2.5;
}

// PB START
.search-container .icon-wap-home,
.search-container .navbar-v-line {
  display: none;
}
.search-small-icon {
  width: 40rpx;
  height: 40rpx;
  margin-bottom: 4px;
} //PB END
</style>
